/**
 * 基于 angular 扩展的 ui 控件
 */
define(function (require, exports, module) {
    var $ = require("jquery");
    var angular = require("angular");
    var _ = require("underscore");
    var storage = require("storage");
    var util = require("util");
    var ui = require("ui");

    var projectSelector = angular.module('filterCombobox', []);

    // 项目树控件
    var projectDirective = function ($compile, $document, $parse) {
        return {
            restrict: 'EA',
            replace: true,
            transclude: true,
            require: '?ngModel',
            templateUrl: function (tElement, tAttrs) {
                return '/ydxs_static/public/js/angular-ui' + (angular.isDefined(tAttrs.multiple) ? '/filterCombobox-multiple.html' : '/filterCombobox.html');
            },
            scope: {
                data: '=data',
                disabled: '=ngDisabled'
            },
            link: function (scope, element, attrs, ngModel, transcludeFn) {
                element = $(element[0]);
                scope.multiple = angular.isDefined(attrs.multiple);
                scope.textField = 'text';
                scope.valueField = attrs.valueField?attrs.valueField:'s_userId';
                var each = function (fn) {
                    if (!scope.data) {
                        return;
                    }
                    for (i = 0; i < scope.data.length; i++) {
                        if (fn(scope.data[i]) === false) {
                            return;
                        }
                    }
                };

                // 根据选项变化设置全选状态和文本
                var updateChecked = function () {
                    var values = [];
                    var texts = [];
                    scope.checkedAll = true;
                    each(function (record) {
                        if (record.checked) {
                            values.push(record[scope.valueField]);
                            texts.push(record[scope.textField]);
                        } else {
                            scope.checkedAll = false;
                        }
                    });

                    scope.text = texts.join(',');
                    scope.value = values;
                };

                // 单选选中
                scope.select = function (record) {
                    scope.text = record[scope.textField];
                    scope.value = record[scope.valueField];
                    if (ngModel) {
                        ngModel.$setViewValue(scope.value);
                    }
                };

                // 多选选中
                scope.checkChanged = function () {
                    updateChecked();
                };

                // 多选选中所有
                scope.checkAllChanged = function (checkedAll) {
                    var values = [];
                    var texts = [];
                    each(function (record) {
                        record.checked = checkedAll;
                        if (checkedAll) {
                            values.push(record[scope.valueField]);
                            texts.push(record[scope.textField]);
                        }
                    });

                    scope.text = texts.join(',');
                    scope.value = values;
                };

                function syncText(val) {
                    scope.text = '';
                    each(function (record) {
                        if (record[scope.valueField] == val) {
                            scope.text = record[scope.textField];
                            return false;
                        }
                    });
                }

                function syncTextMultiple(values) {
                    if (values === undefined) {
                        values = [];
                    }
                    if (typeof values == 'string') {
                        values = values.split(',');
                    }

                    var texts = [];
                    each(function (record) {
                        for (var j = 0; j < values.length; j++) {
                            if (record[scope.valueField] == values[j]) {
                                texts.push(record[scope.textField]);
                                record.checked = true;
                                break;
                            } else {
                                record.checked = false;
                            }
                        }
                    });
                    scope.text = texts.join(',');
                }


                // 监听备选项变化
                scope.$watch('data', function (newValue) {
                    var storageObject;
                    var data = newValue;
                    var val = scope.$parent.$eval(attrs.ngModel);
                    var originalVal = val;

                    if (scope.multiple) {
                        if (data) {
                            if (_.isEmpty(val)) {
                                // 从本地存储读取默认值
                                // 默认全部选中
                                val = [];
                                each(function (record) {
                                    val.push(record[scope.valueField]);
                                });
                            }

                            // 检测值知否存在 data 列表中
                            for (var i = 0; i < val.length; i++) {
                                var found = false;
                                each(function (record) {
                                    if (record[scope.valueField] == val[i]) {
                                        found = true;
                                        return false;
                                    }
                                });

                                if (!found) {
                                    // 未找到的值移除
                                    val.splice(i--, 1);
                                }
                            }
                        }
                    } else {
                        if (data) {
                            // 检测值知否存在 data 列表中
                            var valRecord = _.find(data, function (x) {
                                return x[scope.valueField] == val;
                            });

                            //if (!valRecord) {
                            //    valRecord = _.first(data);
                            //    val = valRecord && valRecord[scope.valueField] || '';
                            //}
                        }
                    }

                    if ((originalVal !== val || !_.isEqual(originalVal, val)) && ngModel) {
                        ngModel.$setViewValue(val);
                    }
                });

                // 监听选中值变化
                scope.$parent.$watch(attrs.ngModel, function (newValue, oldValue) {
                    var val = newValue;
                    if (scope.multiple) {
                        syncTextMultiple(val);
                        updateChecked();
                    } else {
                        syncText(val);
                    }
                });

                // 监听disabled
                if(attrs.uiDisabled){
                    scope.$parent.$watch(attrs.uiDisabled, function (newValue) {
                        scope.disabled = newValue;
                    });
                }

                var inputBox = element.find('.js-select2');
                inputBox.on("click", function (e) {
                    if (scope.disabled) {
                        return;
                    }

                    if (element.hasClass('select-on')) {
                        collapse();
                    } else {
                        open();
                    }
                });

                /**
                 * 判断元素是否在容器内或容器本身
                 * @param {HTMLElement} container
                 * @param {HTMLElement} target
                 * @returns {*|boolean}
                 */
                function isOrHas(container, target) {
                    return $.contains(container, target) || container === target;
                }

                /**
                 * 展开
                 */
                function open() {
                    element.addClass("select-on");
                    $document.on('click',onDocumentClick);
                }

                /**
                 * 收起
                 */
                function collapse() {
                    element.removeClass("select-on");
                    $document.off('click', onDocumentClick);
                }

                var $searchBox = element.find('.search-box-border');
                //点击桌面隐藏弹层
                function onDocumentClick(e) {
                    var target = e.target;
                    if (angular.element(target).hasClass('select-group')
                        || $searchBox[0] && $.contains($searchBox[0], target)) {
                        return;
                    }

                    if (scope.multiple) {
                        if (!isOrHas(element[0], target)) {
                            // 如果触发冒泡的元素不在控件元素之内，则将弹出框收起
                            collapse();

                            if (ngModel && !_.isEqual(scope.value, ngModel.$viewValue)) {
                                ngModel.$setViewValue(scope.value);
                            }
                        }
                    } else {
                        if (!isOrHas(inputBox[0], target)) {
                            // 如果触发冒泡的元素不在控件元素之内，则将弹出框收起
                            collapse();
                        }
                    }

                }

                scope.$on('$destroy', function () {
                    $document.off('click', onDocumentClick);
                    inputBox.off('click');
                });
            }
        };
    };
    projectSelector.directive('uiFiltercombobox', ['$compile', '$document', '$parse', projectDirective]);

    module.exports = projectSelector;
});